package itsm.isperp.framework.utils;

import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.awt.image.CropImageFilter;
import java.awt.image.FilteredImageSource;
import java.awt.image.ImageFilter;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.imageio.ImageIO;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

/**
 * 
 * 
 * 
 * @author lizx
 * @date 2014-1-21
 * @since 1.0
 * 
 */
public class ImageUtils {
	/**
	 * 缩放后裁剪图片方法
	 * 
	 * @param srcImageFile
	 *            源文件
	 * @param x
	 *            x坐标
	 * @param y
	 *            y坐标
	 * @param destWidth
	 *            最终生成的图片宽
	 * @param destHeight
	 *            最终生成的图片高
	 * @param finalWidth
	 *            缩放宽度
	 * @param finalHeight
	 *            缩放高度
	 * @throws IOException
	 */
	public static void abscut(String srcImageFile, String dirImageFile, int x,
			int y, int destWidth, int destHeight) throws IOException {

		Image img;
		ImageFilter cropFilter;
		// 读取源图像
		BufferedImage bi = ImageIO.read(new File(srcImageFile));
		int srcWidth = bi.getWidth(); // 源图宽度
		int srcHeight = bi.getHeight(); // 源图高度
		if (srcWidth >= destWidth && srcHeight >= destHeight) {
			Image image = bi.getScaledInstance(srcWidth, srcHeight,
					Image.SCALE_DEFAULT);
			// 改进的想法:是否可用多线程加快切割速度
			// 四个参数分别为图像起点坐标和宽高
			// 即: CropImageFilter(int x,int y,int width,int height)
			cropFilter = new CropImageFilter(x, y, destWidth, destHeight);
			img = Toolkit.getDefaultToolkit().createImage(
					new FilteredImageSource(image.getSource(), cropFilter));
			BufferedImage tag = new BufferedImage(destWidth, destHeight,
					BufferedImage.TYPE_INT_RGB);
			Graphics g = tag.getGraphics();
			g.drawImage(img, 0, 0, null); // 绘制缩小后的图
			g.dispose();

			File f = new File(dirImageFile);
			if (!f.exists())
				f.mkdirs();
			// 输出为文件
			ImageIO.write(tag, "JPEG", new File(dirImageFile));

		}
	}

	/**
	 * 缩放图像
	 * 
	 * @param srcImageFile
	 *            源图像文件地址
	 * @param result
	 *            缩放后的图像地址
	 * @param scale
	 *            缩放比例
	 * @param flag
	 *            缩放选择:true 放大; false 缩小;
	 * @throws IOException
	 */
	public static void scale(String srcImageFile, String result, int scale,
			boolean flag) throws IOException {

		BufferedImage src = ImageIO.read(new File(srcImageFile)); // 读入文件
		int width = src.getWidth(); // 得到源图宽
		int height = src.getHeight(); // 得到源图长
		if (flag) {
			// 放大
			width = width * scale;
			height = height * scale;
		} else {
			// 缩小
			width = width / scale;
			height = height / scale;
		}
		Image image = src.getScaledInstance(width, height, Image.SCALE_DEFAULT);
		BufferedImage tag = new BufferedImage(width, height,
				BufferedImage.TYPE_INT_RGB);
		Graphics g = tag.getGraphics();
		g.drawImage(image, 0, 0, null); // 绘制缩小后的图
		g.dispose();
		ImageIO.write(tag, "JPEG", new File(result));// 输出到文件流

	}

	/**
	 * 重新生成按指定宽度和高度的图像
	 * 
	 * @param srcImageFile
	 *            源图像文件地址
	 * @param result
	 *            新的图像地址
	 * @param _width
	 *            设置新的图像宽度
	 * @param _height
	 *            设置新的图像高度
	 * @throws IOException
	 */
	public static void scale(String srcImageFile, String result, int _width,
			int _height) throws IOException {
		scale(srcImageFile, result, _width, _height, 0, 0);
	}

	public static void scale(String srcImageFile, String result, int _width,
			int _height, int x, int y) throws IOException {

		BufferedImage src = ImageIO.read(new File(srcImageFile)); // 读入文件

		int width = src.getWidth(); // 得到源图宽
		int height = src.getHeight(); // 得到源图长

		if (width > _width) {
			width = _width;
		}
		if (height > _height) {
			height = _height;
		}
		Image image = src.getScaledInstance(width, height, Image.SCALE_DEFAULT);
		BufferedImage tag = new BufferedImage(width, height,
				BufferedImage.TYPE_INT_RGB);
		Graphics g = tag.getGraphics();
		g.drawImage(image, x, y, null); // 绘制缩小后的图
		g.dispose();
		File f = new File(result);
		if (!f.exists())
			f.mkdirs();
		ImageIO.write(tag, "JPEG", new File(result));// 输出到文件流

	}
	
	public static InputStream BaseToInputStream(String base64string){  
	    ByteArrayInputStream stream = null;
		try {
		    BASE64Decoder decoder = new BASE64Decoder(); 
		    byte[] bytes1 = decoder.decodeBuffer(base64string);  
		    stream = new ByteArrayInputStream(bytes1);  
		} catch (Exception e) {
		// TODO: handle exception
		}
	        return stream;  
	    } 

	public static String GetImageStr(String imgFilePath) {// 将图片文件转化为字节数组字符串，并对其进行Base64编码处理
		byte[] data = null;

		// 读取图片字节数组
		try {
			InputStream in = new FileInputStream(imgFilePath);
			data = new byte[in.available()];
			in.read(data);
			in.close();
		} catch (IOException e) {
			e.printStackTrace();
		}

		// 对字节数组Base64编码
		BASE64Encoder encoder = new BASE64Encoder();
		return encoder.encode(data);// 返回Base64编码过的字节数组字符串
	}
	public static boolean GenerateImage(String imgStr, String imgFilePath) {// 对字节数组字符串进行Base64解码并生成图片
		if (imgStr == null) // 图像数据为空
			return false;
		BASE64Decoder decoder = new BASE64Decoder();
		try {
			// Base64解码
			byte[] bytes = decoder.decodeBuffer(imgStr);
			for (int i = 0; i < bytes.length; ++i) {
				if (bytes[i] < 0) {// 调整异常数据
					bytes[i] += 256;
				}
			}
			// 生成jpeg图片
			OutputStream out = new FileOutputStream(imgFilePath);
			out.write(bytes);
			out.flush();
			out.close();
			return true;
		} catch (Exception e) {
			return false;
		}
	}
}
